﻿using King.Box.Models.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Filters;

namespace King.Box.WebApi.Filter
{
    public class ExceptionHandlerAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            {
                var logContent = string.Format("{0} {1}", DateTime.Now, actionExecutedContext.Exception.Message);
                Console.WriteLine(logContent);
            }

            var messageContent = JsonConvert.SerializeObject(ResponseData.Failtrue(actionExecutedContext.Exception.Message));
            actionExecutedContext.Response = new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.InternalServerError,
                Content = new StringContent(
                    messageContent
                    , Encoding.UTF8
                    ,"application/json")
            };

            base.OnException(actionExecutedContext);
        }
    }
}
